import ArticleItem from '../ArticleItem'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
// import { useEffect } from 'react'
import { getArticleList, getNewArticleList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'

type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  const dispatch = useDispatch()
  const { channelArticles, } = useSelector((state: RootState) => state.home)
  const { articles = [], timestamp } = channelArticles[channelId] || {}
  const history = useHistory()

  // useEffect(() => {
  //   dispatch(getArticleList(channelId, Date.now() + ''))
  // }, [dispatch, channelId])


  // 上拉加载
  const hasMore = (timestamp !== null)
  // 必须返回一个Promise对象
  const loadMore = async () => {
    await dispatch(getArticleList(channelId, timestamp || Date.now()))
  }

  // 下拉刷新
  const onRefresh = async () => {
    // console.log('加载最新的数据')
    await dispatch(getNewArticleList(channelId, Date.now()))
  }
  return (
    <div className={styles.root}>
      {/* 下拉刷新 */}
      <PullToRefresh onRefresh={onRefresh}>
        {/* 文章列表中的每一项 */}
        {articles.map((item) => (
          <div className="article-item" key={item.art_id}
            onClick={() => {
              history.push(`/article/${item.art_id}`)
            }}>
            <ArticleItem article={item} />
          </div>
        ))}
        {/* 无限滚动 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
